package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.Utils.ValidateCodeUtils;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendmsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phoneN = user.getPhone();
        if (StringUtils.isNotEmpty(phoneN)) {
            //生成验证码
            String captcha = ValidateCodeUtils.generateValidateCode(4).toString();

            session.setAttribute(phoneN, captcha);
            log.info(captcha);
            return R.success("发送成功");
        }
        return R.error("发送失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        //获取手机号
        log.info(map.toString());
        String phoneN = map.get("phone").toString();
        //获取验证码
        String captcha = map.get("code").toString();
        //从Session中获取保存的验证码
        Object attribute = session.getAttribute(phoneN);
        //比对验证码
        if (attribute != null && attribute.equals(captcha)) {
            //比对成功，登录
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phoneN);

            User user = userService.getOne(queryWrapper);

            if (user == null) {
                //判断是否为新用户，如是则自动完成注册
                user = new User();
                user.setPhone(phoneN);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
            return R.success(null);
        }
        return R.error("登陆失败");
    }

    @PostMapping("/loginout")
    public R<String> out(HttpServletRequest request){

        request.getSession().removeAttribute("/loginout");

        return R.success("退出成功");
    }


}

